package com.zmjmall.demo.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zmjmall.demo.api.ProductAttrbuteService;
import com.zmjmall.demo.api.ProductPropertyService;
import com.zmjmall.demo.utils.ResultVOUtil;
import com.zmjmall.demo.vo.ResultVO;
import com.zmjmall.demo.vo.SkuAttributesVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author zmj
 * @version 2018/7/4
 */
@RestController
@RequestMapping("/productProperty")
@Slf4j
public class ProductPropertyController {

    @Reference
    private ProductPropertyService propertyService;

    @Reference
    private ProductAttrbuteService attrbuteService;

    @GetMapping("/{categoryId}")
    @ResponseBody
    public ResultVO findAll(@PathVariable String categoryId) {
        List<SkuAttributesVO> attributesVOS = propertyService.findByCategoryId(categoryId);
        Map<String,SkuAttributesVO> map = new HashMap<>();
        for (SkuAttributesVO attribute:attributesVOS) {
            map.put(attribute.getPropertyId(),attribute);
        }

        JSONArray result = new JSONArray();

        Iterator<Map.Entry<String, SkuAttributesVO>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            JSONArray array = new JSONArray();
            JSONObject propertyObject = new JSONObject();
            Map.Entry<String, SkuAttributesVO> tempMap = iterator.next();
            for (SkuAttributesVO attribute:attributesVOS) {
                if(attribute.getPropertyId().equals(tempMap.getKey())) {
                    JSONObject attributeObject = new JSONObject();
                    attributeObject.put("attributeId",attribute.getAttributeId());
                    attributeObject.put("attributeName",attribute.getAttributeName());
                    array.add(attributeObject);
                }
            }
            propertyObject.put("propertyId",tempMap.getKey());
            propertyObject.put("propertyName",tempMap.getValue().getPropertyName());
            propertyObject.put("attribudes",array);
            result.add(propertyObject);
        }

        return ResultVOUtil.success(result);
    }

}
